import { ref } from 'vue'
import { logoutApi } from '~@/api/common/login'
import type { MenuInfo, TenantInfo, TenantList, UserInfo } from '~@/api/portal'
import { current, joinedTenantList } from '~@/api/portal'
import type { MenuData } from '~@/layouts/basic-layout/typing'
import { rootRoute } from '~@/router/constant'
import { generateFlatRoutes, generateRoutes } from '~@/router/generate-route'

export const useUserStore = defineStore('user', () => {
    const routerData = shallowRef()
    const menuData = shallowRef<MenuData>([])
    const menuInfo = shallowRef<MenuInfo>([])
    const userInfo = shallowRef<UserInfo>()
    const tenantList = ref<TenantList>([])
    const tenantInfo = ref<TenantInfo>({})
    const tenant = useTenant()
    const token = useAuthorization()
    const avatar = computed(() => `/${userInfo.value?.avatar}`)
    const nickname = computed(() => userInfo.value?.name ?? userInfo.value?.username)
    const roles = computed(() => userInfo.value?.label)

    const generateDynamicRoutes = async () => {
        const { menuData: treeMenuData, routeData } = await generateRoutes(menuInfo.value)
        menuData.value = treeMenuData
        routerData.value = {
            ...rootRoute,
            children: generateFlatRoutes(routeData),
        }
        return routerData.value
    }

    const getTenantList = async () => {
        if (!userInfo.value) {
            tenantList.value = []
        }
        else {
            const { data } = await joinedTenantList(userInfo.value?.id)
            if (data)
                tenantList.value = data
            else
                tenantList.value = []
        }
        if (tenantList.value.length > 0) {
            const currentTenant = tenant.value || tenantInfo.value.id
            if (currentTenant) {
                let contained = false
                for (const item of tenantList.value) {
                    if (item.id === currentTenant) {
                        tenantInfo.value = item
                        contained = true
                        break
                    }
                }
                if (!contained)
                    tenantInfo.value = tenantList.value[0]
            }
            else {
                tenantInfo.value = tenantList.value[0]
            }
        }
        else {
            tenantInfo.value = {}
        }
        tenant.value = tenantInfo.value?.id
        return tenantList.value
    }
    // 获取用户信息
    const getUserInfo = async () => {
        // 获取用户信息
        const { data } = await current()
        if (data) {
            userInfo.value = data.user
            menuInfo.value = data.menu || []
        }
        await getTenantList()
    }

    const exchangeTenant = async (item: TenantInfo) => {
        tenant.value = item.id
        tenantInfo.value = item
        window.location.reload()
    }

    const logout = async () => {
        // 退出登录
        // 1. 清空用户信息
        try {
            await logoutApi()
        }
        finally {
            token.value = null
            tenant.value = null
            userInfo.value = undefined
            routerData.value = undefined
            menuData.value = []
        }
    }

    return {
        userInfo,
        roles,
        tenantList,
        tenantInfo,
        getUserInfo,
        getTenantList,
        exchangeTenant,
        logout,
        routerData,
        menuData,
        generateDynamicRoutes,
        avatar,
        nickname,
    }
})
